import {Layout, Menu} from "antd";
import React, {useState, FC, useEffect, useContext} from "react";
import {useMenuStore} from "@/store/menuStore.tsx";
import {useNavigate} from "react-router-dom";
import SlSiderLogo from "@/components/SlSider/SlSiderLogo.tsx";
import {StyleContext} from "@/context/style-context.tsx";
const { Sider } = Layout;
import style from "./index.module.scss"
interface ISiderProps {
    collapsed: boolean;
}
const SlSider: FC<ISiderProps> = ({collapsed}) => {
    const { namespace, elNamespace } = useContext(StyleContext);
    const [selectKeys, setSelectKeys] = useState<any[]>([]);
    const navigate = useNavigate();
    const {getMenuItems, isMenuLoaded} = useMenuStore();
    const menuItems = getMenuItems();
    const styleList = {
        wrapper: `${namespace}-sider`,
        menu: `${namespace}-sider-menu`,
        logo: `${namespace}-sider-logo`
    }
    const getDefaultPath = (data: any[], path: any, selectItems: any[]) => {
        for (let i = 0; i < data.length; i++) {
            if (path.includes(data[i].path)) {
                selectItems.push(data[i]);
            }
            if (data[i].children && data[i].children.length) {
                getDefaultPath(data[i].children, path, selectItems);
            }
        }
    };
    // 获取当前选中的菜单项
    const getSelectedKeys = () => {
        if (!isMenuLoaded) return [];
        const path = location.pathname;
        const selectItems: any = [];
        getDefaultPath(menuItems, path, selectItems);
        return selectItems ? selectItems.map((ele: any) => ele.key) : [];
    };

    // 处理菜单点击
    const handleMenuClick = (options: any) => {
        const { item } = options;
        if (item.props.path) {
            navigate(item.props.path);
        }
    };

    useEffect(() => {
        if (isMenuLoaded) {
            const keys = getSelectedKeys();
            setSelectKeys(keys);
        }
    }, [location, navigate, isMenuLoaded]);
    return (
        <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            className={style[styleList.wrapper]}
        >
            {/*<SlSiderLogo className={style[styleList.logo]} collapsed={collapsed}/>*/}
            {isMenuLoaded ? (
                <Menu
                    theme="dark"
                    mode="inline"
                    selectedKeys={selectKeys}
                    defaultOpenKeys={selectKeys}
                    inlineCollapsed={collapsed}
                    items={menuItems}
                    onClick={handleMenuClick}
                />
            ) : (
                <div className="flex flex-col justify-center items-center p-4 text-white">
                    <div className="spinner"/>
                    <p className="mt-3">加载菜单中...</p>
                </div>
            )}
        </Sider>
    )
}
export default SlSider;